package com.db.user.filter;

import com.db.user.entity.User;
import com.db.user.utils.GetJwtToken;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

/**
 * 作者：Bin
 * 时间：2023/10/16
 * 描述：键盘敲烂，薪资过万
 */
public class TokenFilter extends BasicAuthenticationFilter {
    public TokenFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String token = request.getHeader("token");
        try {
            //获取用户主体
            User verify = GetJwtToken.verify(token);
            //用户的权限列表
            Collection<GrantedAuthority> authorities = new ArrayList<>();
            for (String role : verify.getRoles()) {
                authorities.add(new SimpleGrantedAuthority(role));
            }

            //将用户信息存储到SecurityContext中
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(verify,null,authorities);
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //放行
        chain.doFilter(request,response);
        //清空SecurityContext
        SecurityContextHolder.clearContext();
    }
}
